package com.example.tool.actions;

import com.example.tool.entity.ConfigEntity;
import com.example.tool.module.ModuleInformation;
import com.example.tool.module.ModuleInputEnum;
import com.example.tool.ui.HToolIcon;
import com.example.tool.utils.ActionToolUtil;
import com.example.tool.utils.FileUtil;
import com.intellij.openapi.actionSystem.ActionUpdateThread;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.DefaultActionGroup;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.JavaDirectoryService;
import com.intellij.psi.PsiDirectory;
import com.intellij.psi.PsiManager;
import com.intellij.psi.PsiPackage;
import org.jetbrains.annotations.NotNull;

import java.nio.file.Path;
import java.util.List;
import java.util.Map;

public class BuildGroup extends DefaultActionGroup {

  public BuildGroup() {
    super(ModuleInformation.BUILD_GROUP, null, HToolIcon.MODULE_ICON);
    getTemplatePresentation().setPopupGroup(true);
  }

  @Override
  public void update(@NotNull AnActionEvent e) {
    ActionToolUtil.actionIsVisible(e);
  }


  @Override
  public @NotNull ActionUpdateThread getActionUpdateThread() {
    return ActionUpdateThread.BGT;
  }

  public static void buildPre(@NotNull AnActionEvent anActionEvent, Runnable runnable) throws Exception {
    buildPre(anActionEvent, null, runnable);
  }

  /**
   * @param anActionEvent 菜单事件
   * @param isPackage     指定包路径下 com.example.xxx
   * @param runnable      要执行的具体方法
   */
  public static void buildPre(@NotNull AnActionEvent anActionEvent, String isPackage, Runnable runnable) throws Exception {
    Project project = anActionEvent.getProject();
    List<PsiDirectory> psiDirectories = ActionToolUtil.actionSelectPath(anActionEvent);
    if (psiDirectories.size() != 1) {
      throw new Exception("请选中一个文件（或文件夹）再进行操作");
    }
    if (isPackage != null) {// 是否需要在固定的包下面创建文件
      PsiDirectory psiDirectory = psiDirectories.get(0);
      JavaDirectoryService instance = JavaDirectoryService.getInstance();
      PsiPackage psiPackage = instance.getPackage(psiDirectory);
      if (psiPackage != null) {
        String qualifiedName = psiPackage.getQualifiedName();
        if (!qualifiedName.startsWith(isPackage)) {
          String textParse = ModuleInformation.textParse(ModuleInformation.TIP_PACKAGE, isPackage);
          throw new Exception(textParse);
        }
      }
    }
    ConfigEntity configEntity = ActionToolUtil.getInformation(project);
    if (configEntity != null) {
      runnable.run();
    } else {
      ActionToolUtil.noConfig(project);
    }
  }

  public static void createSpringBean(Project project, Object object, String endString, Map<ModuleInputEnum, String> replaceParam) throws Exception {
    createSpringBean(project, object, endString, replaceParam, "/xml/spring/spring-xxx-other.xml.sample");
  }

  public static void createSpringBean(Project project, Object object, String endString, Map<ModuleInputEnum, String> replaceParam, boolean isOpen) throws Exception {
    createSpringBean(project, object, endString, replaceParam, "/xml/spring/spring-xxx-other.xml.sample", isOpen);
  }

  public static void createSpringBean(Project project, Object object, String endString, Map<ModuleInputEnum, String> replaceParam, String contentPath) throws Exception {
    createSpringBean(project, object, endString, replaceParam, contentPath, false);
  }

  /**
   * 创建指定路径
   * @param project      项目对象
   * @param object       操作对象
   * @param endString    spring后缀
   * @param replaceParam 替换参数
   * @param isOpen       是否打开对应文件
   */
  public static void createSpringBean(Project project, Object object, String endString, Map<ModuleInputEnum, String> replaceParam, String contentPath, boolean isOpen) throws Exception {
    ConfigEntity configEntity = ActionToolUtil.getInformation(project);
    String pluginID = configEntity.getPluginID();
    PsiDirectory psiBaseDir = createDirectories(project, object, "WEB-INF", "cfgHome", "plugin", pluginID, "spring");
    FileUtil.createXml(project, psiBaseDir, "spring-" + pluginID + "-" + endString, replaceParam, contentPath, isOpen);
  }


  public static PsiDirectory createDirectories(Project project, Object object, String... paths) throws Exception {
    String basePath = project.getBasePath();
    if (basePath != null) {
      // 创建Xml
      Path path = Path.of(basePath);
      PsiManager psiManager = PsiManager.getInstance(project);
      LocalFileSystem localFileSystem = LocalFileSystem.getInstance();
      VirtualFile virtualFileBuildPath = localFileSystem.findFileByNioFile(path);
      ConfigEntity configEntity = ActionToolUtil.getInformation(project);
      String buildPath = configEntity.getBuildPath();
      String[] combinedPaths = new String[paths.length + 1];
      combinedPaths[0] = buildPath;
      System.arraycopy(paths, 0, combinedPaths, 1, paths.length);
      VirtualFile virtualFile = FileUtil.createDirectories(object, virtualFileBuildPath, combinedPaths);
      virtualFile.refresh(false, true);
      return psiManager.findDirectory(virtualFile);
    }
    return null;
  }
}
